﻿package bdz.common.managers
{
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	/**
	 * ...
	 * @author ...
	 */
	public class CacheLoader extends EventDispatcher 
	{
		private static var instance:CacheLoader;
		
		private var cached:Dictionary;
		public function CacheLoader(se:SingletonEnforcer) {
			super();
		}
		public static function getCache():CacheLoader {
			if (!instance) {
				instance = new CacheLoader(new SingletonEnforcer());
				instance.initialize();
			}
			return instance;
		}
		private function initialize():void {
			cached = new Dictionary();
		}
		public function loadSomething(obj:*, completeEvent:String, preloadEvent:String, url:String, bloadedProp:String = "bytesLoaded", btotalProp:String = "bytesTotal"):* {
			if (cached[url]) {
				if (cached[url].loaded){
					return cached[url];
				}
			}
			cached[url] = {baseObject:obj, loaded:false, progress:0};
			obj.addEventListener(preloadEvent,  function() { cached[url].progress = arguments[0][bloadedProp]/arguments[0][btotalProp];});
			obj.addEventListener(completeEvent, function() { cached[url].loaded = true;} );
			return null;
		}
	}
}
/**
 * @private
 * 
 */
internal class SingletonEnforcer{}
